package com.ericpol2;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class PageBase {

	protected int Timeout = 30;
	private WebDriver driver;
	private StringBuffer verificationErrors = new StringBuffer();

	public PageBase() {
		super();
	}

	@BeforeMethod
	public void setUp() throws Exception {
		driver = new HtmlUnitDriver(); // new FirefoxDriver() odpal Firefox
		driver.manage().timeouts().implicitlyWait(Timeout, TimeUnit.SECONDS); // czekaj 30s na oczekiwany element
	}
	protected WebElement findElement(String field) {			
		return driver.findElement(By.xpath(field));
	}
	
	protected void assertThatElementNotPresent(String field) {
		try{
			driver.findElement(By.xpath(field));
			Assert.fail();
		} catch(NoSuchElementException e){
		}
	}
	
	protected void insertText(String field,String text){
		WebElement element = findElement(field);
		element.clear();
		element.sendKeys(text);		
	}
	protected void assertLinkIsOnPage(String text) {
		AssertJUnit.assertEquals(text, driver.findElement(By.linkText(text)).getText());
	}
	
	protected void assertIsLogoutVisible(String field) {
		AssertJUnit.assertEquals("Logout",findElement(field).getText());
	}
	
	protected void chooseAddress(String link) {
		driver.get(link);
	}

	protected void click(By by) {
		driver.findElement(by).click();
	}
	
	protected void clickXPath(String field) {
		driver.findElement(By.xpath(field)).click();
	}

	@AfterMethod
	public void tearDown() throws Exception {
		driver.quit(); // zamknij przegladarke
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			Assert.fail(verificationErrorString);
		}
	}

}